package net.kucukcezve.tabu.menu;

import java.util.Vector;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import net.kucukcezve.tabu.TabuMIDlet;

/**
 *
 * @author cemal
 * @mail : cemal.yilmaz@gmail.com
 */
public class MenuCanvas extends Canvas {

    private TabuMIDlet midlet;
    private Vector menuItems;
    private Font menuFont;
    private int fontHeight;
    private int selectedIndex;

    public MenuCanvas(TabuMIDlet _midlet, Vector _items) {
        midlet = _midlet;
        menuItems = _items;
        menuFont = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED, Font.SIZE_LARGE);
        fontHeight = menuFont.getHeight() + 3;
    }

    protected void paint(Graphics g) {
        int w = getWidth();
        int h = getHeight();

        g.setColor(0xffffff);
        g.fillRect(0, 0, w, h);

        int base = (h - menuItems.size() * fontHeight) / 2;
        for (int i = 0; i < menuItems.size(); i++) {
            if (selectedIndex == i) {
                g.setColor(0xAAAAAA);
            } else {
                g.setColor(0x0);
            }
            String menu = (String) menuItems.elementAt(i);
            g.drawString(menu, w / 2, base, Graphics.TOP | Graphics.HCENTER);
            base += fontHeight;
        }
    }

    private void handleSelection() {
        if (selectedIndex == 0) {
            midlet.newGame();
        }
    }

    protected void keyPressed(int keyCode) {

        int gameCode = getGameAction(keyCode);
        switch (gameCode) {
            case Canvas.UP:
                System.out.println("Up");
                if (selectedIndex > 0) {
                    selectedIndex--;
                    repaint();
                }
                break;
            case Canvas.DOWN:
                System.out.println("Down");
                if (selectedIndex < menuItems.size() - 1) {
                    selectedIndex++;
                    repaint();
                }
                break;
            case Canvas.FIRE:
                System.out.println("Fire");
                handleSelection();
                break;
        }
    }
}
